package com.example.beixiangsuapp.bxs.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 基于okhttp的网络请求工具类
 * 
 * @author Administrator
 * 
 */
public class netutils {

	public static netutils instance = null;
	private OkHttpClient mokhttp;
	public static final MediaType JSON = MediaType
			.parse("application/json; charset=utf-8");
	public static String TAG = "httprequest";
	public static String sessionid = null;
	public int isAddheader = 0;
	public int FAILED_CODE = -1;

	public static netutils getInstance() {
		if (instance == null) {
			instance = new netutils();
		}
		return instance;
	}

	public netutils() {
		mokhttp = new OkHttpClient().newBuilder().connectTimeout(30*1000, TimeUnit.SECONDS).build();

	}

	/**
	 * get请求
	 * 
	 * @param url
	 *            --url
	 * @param map
	 *            --参数，map集合
	 * @param mhandler
	 *            --处理UI的handler
	 * @param msgwhat
	 *            --标识返回信息的int值
	 */
	public void getFromServer(String url, Map<String, Object> map,
			final Handler mhandler, final int msgwhat) {
		String finalurl = url + parseMap(map);
		Request request = new Request.Builder().url(finalurl).get().build();
		mokhttp.newCall(request).enqueue(new Callback() {
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				String response = arg1.body().string();
				int code = arg1.code();
				if (code == 200) {
					Message msg = Message.obtain();
					msg.what = msgwhat;
					msg.obj = response;
					mhandler.sendMessage(msg);
				} else if (code == 404) {

					failed(mhandler, "连接超时，请稍后重试101");
				} else if (code == 500) {

					failed(mhandler, "连接超时，请稍后重试102");
				} else {

					failed(mhandler, "连接超时，请稍后重试103");
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub

				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}
	public void getFromDialog(String url, Map<String, Object> map,
							  final Handler mhandler, final int msgwhat, final Dialog dialog, final Context context) {
		if (!CommonUtils.checkNetworkInfo(context)) {
			if (dialog != null) {
				dialog.dismiss();
			}
			failed(mhandler, "您的网络已断开，请检查网络后再试!");
			return;
		}
		String finalurl = url + parseMap(map);
		Request request = new Request.Builder().url(finalurl).get().build();
		mokhttp.newCall(request).enqueue(new Callback() {
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				String response = arg1.body().string();
				int code = arg1.code();
				if (code == 200) {
					Message msg = Message.obtain();
					msg.what = msgwhat;
					msg.obj = response;
					mhandler.sendMessage(msg);
				} else if (code == 404) {
					if (dialog != null) {
						dialog.dismiss();
					}
					failed(mhandler, "连接超时，请稍后重试101");
				} else if (code == 500) {
					if (dialog != null) {
						dialog.dismiss();
					}
					failed(mhandler, "连接超时，请稍后重试102");
				} else if (code == 502 || code == 504) {
					if (dialog != null) {
						dialog.dismiss();
					}
					failed(mhandler, "连接超时，请稍后重试103");
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				if (dialog!=null){
					dialog.dismiss();
				}
				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}

	/**
	 * get请求--session
	 * 
	 * @param url
	 *            --url
	 * @param map
	 *            --参数，map集合
	 * @param mhandler
	 *            --处理UI的handler
	 * @param msgwhat
	 *            --标识返回信息的int值
	 */
	public void getFromServerSession(String url, Map<String, Object> map,
			final Handler mhandler, final int msgwhat) {

		String finalurl = url + parseMap(map);
		Request request = new Request.Builder().url(finalurl).get()
				.addHeader("Cookie", "JSESSIONID=" + sessionid).build();
		mokhttp.newCall(request).enqueue(new Callback() {
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				initCookie(arg1);
				String response = arg1.body().string();
				int code = arg1.code();
				if (code == 200) {
					Message msg = Message.obtain();
					msg.what = msgwhat;
					msg.obj = response;
					mhandler.sendMessage(msg);
				} else if (code == 404) {

					failed(mhandler, "连接超时，请稍后重试101");
				} else if (code == 500) {

					failed(mhandler, "连接超时，请稍后重试102");
				} else if (code == 502 || code == 504) {

					failed(mhandler, "连接超时，请稍后重试103");
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            --url
	 * @param obj
	 *            --参数，JSONObject格式
	 * @param mhandler
	 *            --处理UI线程的handler
	 * @param msgwhat
	 *            --标识返回结果的int值
	 */
	public  void postToServer(String url, JSONObject obj,
			final Handler mhandler, final int msgwhat,Context context) {
		if (!CommonUtils.checkNetworkInfo(context)) {
			failed(mhandler, "您的网络已断开，请检查网络后再试!");
			return;
		}


		RequestBody body = RequestBody.create(JSON, obj.toString());

		Request request = new Request.Builder().url(url).post(body).build();
		mokhttp.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				String response = arg1.body().string();
				int code = arg1.code();
				if (code == 200) {
					Message msg = Message.obtain();
					msg.what = msgwhat;
					msg.obj = response;
					mhandler.sendMessage(msg);
				} else if (code == 404) {

					failed(mhandler, "连接超时，请稍后重试101");
				} else if (code == 500) {

					failed(mhandler, "连接超时，请稍后重试102");
				} else if (code == 502 || code == 504) {

					failed(mhandler, "连接超时，请稍后重试103");
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}

	public void postToDialog(String url, JSONObject obj,
							 final Handler mhandler, final int msgwhat, final Dialog dialog, final Context context){
		if (!CommonUtils.checkNetworkInfo(context)) {
			if (dialog != null) {
				dialog.dismiss();
			}
			failed(mhandler, "您的网络已断开，请检查网络后再试!");
			return;
		}

		RequestBody body = RequestBody.create(JSON, obj.toString());

		Request request = new Request.Builder().url(url).post(body).build();
		mokhttp.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				String response = arg1.body().string();
				int code = arg1.code();
				if (code == 200) {
					Message msg = Message.obtain();
					msg.what = msgwhat;
					msg.obj = response;
					mhandler.sendMessage(msg);
				} else if (code == 404) {
					if (dialog != null) {
						dialog.dismiss();
					}
					failed(mhandler, "连接超时，请稍后重试101");
				} else if (code == 500) {
					if (dialog != null) {
						dialog.dismiss();
					}
					failed(mhandler, "连接超时，请稍后重试102");
				} else if (code == 502 || code == 504) {
					if (dialog != null) {
						dialog.dismiss();
					}
					failed(mhandler, "连接超时，请稍后重试103");
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				if (dialog!=null){
					dialog.dismiss();
				}
				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}

	/**
	 * post请求--session
	 * 
	 * @param url
	 *            --url
	 * @param obj
	 *            --参数，JSONObject格式
	 * @param mhandler
	 *            --处理UI线程的handler
	 * @param msgwhat
	 *            --标识返回结果的int值
	 */
	public void postToServerWithSession(String url, JSONObject obj,
			final Handler mhandler, final int msgwhat, final Dialog dialog) {
		RequestBody body = RequestBody.create(JSON, obj.toString());

		Request request = new Request.Builder().url(url).post(body)
				.addHeader("Cookie", "JSESSIONID=" + sessionid).build();
		mokhttp.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				initCookie(arg1);
				String response = arg1.body().string();
				Message msg = Message.obtain();
				msg.what = msgwhat;
				msg.obj = response;
				mhandler.sendMessage(msg);

				if (dialog!=null){
					dialog.dismiss();
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub

				if (dialog!=null){
					dialog.dismiss();
				}
				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}

	public String parseMap(Map<String, Object> map) {
		StringBuffer buffer = new StringBuffer("");
		String result;
		if (map != null) {
			buffer.append("?");
			Set<String> keySet = map.keySet();
			for (String key : keySet) {
				Object value = map.get(key);
				buffer.append(key + "=" + value + "&");
			}
			result = buffer.substring(0, buffer.length() - 1);
		} else {
			result = "";
		}
		return result;
	}

	public void postStringToServer(String url, String obj,
			final Handler mhandler, final int msgwhat) {
		RequestBody body = RequestBody.create(JSON, obj);
		Request request = new Request.Builder().url(url).post(body).build();
		mokhttp.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				String response = arg1.body().string();
				Message msg = Message.obtain();
				msg.what = msgwhat;
				msg.obj = response;
				mhandler.sendMessage(msg);
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				failed(mhandler, "连接服务器超时，请重试");
			}
		});
	}

	public static void initCookie(Response response) {
		Headers headers = response.headers();
		for (int j = 0; j < headers.size(); j++) {
			if ("Set-Cookie".equals(headers.name(j))) {
				String value = headers.value(j);
				value = value.substring(value.indexOf("=") + 1,
						value.indexOf("; P"));
				if (!value.equals("deleteMe")) {
					sessionid = value;
				}

				break;
			}
		}
	}

	/**
	 * 上传图片的通用方法
	 * 
	 * @param type
	 *            --1、代理商多媒体红包 2、商户端红包图片 3、商户身份证照片 4、商户营业执照 5、商户授权函 6、商户门头照
	 *            7、商户环境照 8、用户身份证照 9、用户头像 10、营业员头像 11、代理商头像 12、合伙人头像
	 * @param base64
	 *            --需要提交的图片的Base64格式
	 */
	public void upLoadingImg(String url, int type, String base64,
			Handler mhandler, int msgwhat) {
		try {
			JSONObject params = new JSONObject();
			params.put("type", type);
			params.put("img", base64);
			postStringToServer(url, params.toString(), mhandler, msgwhat);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void failed(Handler handler, String msgStr) {
		Message msg = Message.obtain();
		msg.what = FAILED_CODE;
		msg.obj = msgStr;
		handler.sendMessage(msg);
	}
	//判断网络是否可用
	public  boolean ping() {

		String result = null;
		try {
			String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
			Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
			// 读取ping的内容，可以不加
			InputStream input = p.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(input));
			StringBuffer stringBuffer = new StringBuffer();
			String content = "";
			while ((content = in.readLine()) != null) {
				stringBuffer.append(content);
			}
			Log.d("------ping-----", "result content : " + stringBuffer.toString());
			// ping的状态
			int status = p.waitFor();
			if (status == 0) {
				result = "success";
				return true;
			} else {
				result = "failed";
			}
		} catch (IOException e) {
			result = "IOException";
		} catch (InterruptedException e) {
			result = "InterruptedException";
		} finally {
			Log.d("----result---", "result = " + result);
		}
		return false;
	}
}
